<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminUser;
use App\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;

class PermissionController extends Controller
{
    protected $guard_name = 'web';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page = Permission::where(['pid'=>0])
            ->with('subPermissions')
            ->paginate(10);
        $count = Permission::count();//
        return view('Admin.Permission.index',compact('page','count'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $page = Permission::where(['pid'=>0])
            ->with('subPermissions')
            ->get();
        return view('Admin.Permission.create',compact('page'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(),[
            'name'=>'required',
            'describe'=>'required',
            'sel_Sub'=>'required',
//            'route'=>'required'
        ]);
        if(!$validate->fails()) {
            $exist = Permission::where([['name','=',$request->name],['route','<>','']])
                ->first();
            if(empty($exist))
            {
                    if ($request->route) {//栏目添加
                        $requestType = $request->requestType ? $request->requestType : 'get';
                        $describe = $request->describe;
                        $insert = Permission::create(
                            ['name' => $request->type == 'group' ? $request->name . '.index' : $request->name, 'guard_name' => $this->guard_name, 'describe' => $describe, 'pid' => $request->sel_Sub, 'route' => ($request->type == 'group') ? $request->route . '/index' : $request->route, 'type' => $requestType, 'created_at' => date('Y-m-d', time()), 'updated_at' => date('Y-m-d', time())]
                        );
                        if ($insert && $request->type == 'group') {//默认添加群组
                            $insertAll = \Spatie\Permission\Models\Permission::insert([
                                ['name' => $request->name . '.create', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-新增', 'pid' => $insert->id, 'route' => $request->route . '/create', 'type' => 'get', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())],
                                ['name' => $request->name . '.show', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-查看', 'pid' => $insert->id, 'route' => $request->route . '/id', 'type' => 'get', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())],
                                ['name' => $request->name . '.edit', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-编辑', 'pid' => $insert->id, 'route' => $request->route . '/id/edit', 'type' => 'get', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())],
                                ['name' => $request->name . '.destroy', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-删除', 'pid' => $insert->id, 'route' => $request->route . '/id', 'type' => 'delete', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())],
                                ['name' => $request->name . '.store', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-保存', 'pid' => $insert->id, 'route' => $request->route, 'type' => 'post', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())],
                                ['name' => $request->name . '.update', 'guard_name' => $this->guard_name, 'describe' => $request->describe . '-更新', 'pid' => $insert->id, 'route' => $request->route . '/id', 'type' => 'put', 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time())]
                            ]);
                            if (!$insertAll) {
                                $this->set('code', 1);
                                $this->set('message', '系统错误');
                            }
                        } else {
                            $this->set('code', 1);
                            $this->set('message', '系统错误');
                        }
                    } else {//栏目分组
                        $insert = Permission::create(['name' => $request->name, 'guard_name' => $this->guard_name, 'describe' => $request->describe, 'pid' => $request->sel_Sub, 'route' => $request->route]);
                        /*if (!$insert) {
                            $this->set('code', 1);
                            $this->set('message', '系统错误');
                        }*/
                    }
                /*超级管理员授权*/
                $user = AdminUser::find(1);
                $permission = \Spatie\Permission\Models\Permission::getPermissions();
                $user->syncPermissions($permission->pluck('name'));
                /*超级管理员授权*/
            }else{
                $this->set('code', 1);
                $this->set('message', '已存在');
            }
        }else{
            $this->set('code',1);
            $this->set('message','参数错误');
        }
        return $this->ajaxResponse();

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //完整数据
        $page = Permission::where(['pid'=>0])
            ->with('subPermissions')
            ->paginate(10);
        //详情
        $show = Permission::with('parentsPermission')->find($id);
        return view('Admin.Permission.edit',compact('page','show'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $show = Permission::findOrFail($id);
        if($show)
        {
            $name = $request->name ? $request->name : $show->name;
            $pid = $request->sel_Sub ? $request->sel_Sub : $show->pid;
            $describe = $request->describe ? $request->describe : $show->describe;
            $route = $request->route ? $request->route : $show->route;
            $type = $request->requestType?$request->requestType:$show->type;
            $update = Permission::where(['id'=>$id])
                ->update(['name'=>$name,'pid'=>$pid,'describe'=>$describe,'route'=>$route,'type'=>$type]);
            if(!$update)
            {
                $this->set('code',1);
                $this->set('message','操作失败');
            }
        } else{
            $this->set('code',1);
            $this->set('message','暂无该记录');
        }
        return $this->ajaxResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if($id)
        {
            $res = Permission::find($id);
            $res->delete();
            if(!$res->trashed())
            {
                $this->set('code',1);
                $this->set('message','删除失败');
            }
        }else{
            $this->set('code',1);
            $this->set('message','暂无该数据');
        }
        return $this->ajaxResponse();
    }
}
